package com.molichuxing.services.business.service.impl;

import javax.annotation.Resource;

import com.molichuxing.services.business.dto.response.CarBizDto;
import com.molichuxing.services.infrastructure.bean.CarBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.services.business.convertor.Convert;
import com.molichuxing.services.business.dto.request.create.VehicleCreateBizDto;
import com.molichuxing.services.business.dto.request.modify.DeliveryModifyBizDto;
import com.molichuxing.services.business.dto.request.modify.ReturnCarModifyBizDto;
import com.molichuxing.services.business.dto.response.CarDetailBizDto;
import com.molichuxing.services.business.dto.response.CarPendStatisticsDto;
import com.molichuxing.services.business.service.CarBizService;
import com.molichuxing.services.business.service.CarCheckBizService;
import com.molichuxing.services.infrastructure.dto.request.create.HandoverCreateDto;
import com.molichuxing.services.infrastructure.dto.response.CarDetailDto;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.dto.response.HandoverDto;
import com.molichuxing.services.infrastructure.dto.response.LicencePlateDto;
import com.molichuxing.services.infrastructure.service.AccidentService;
import com.molichuxing.services.infrastructure.service.CarDetailService;
import com.molichuxing.services.infrastructure.service.CarService;
import com.molichuxing.services.infrastructure.service.CarViolationService;
import com.molichuxing.services.infrastructure.service.CheckService;
import com.molichuxing.services.infrastructure.service.HandoverService;
import com.molichuxing.services.infrastructure.service.InsuranceService;
import com.molichuxing.services.infrastructure.service.LicencePlateService;
import com.molichuxing.services.infrastructure.service.MaintenanceService;
import com.molichuxing.services.infrastructure.service.YearlyInspectService;
import com.molichuxing.services.property.CarAccidentStatusEnum;
import com.molichuxing.services.property.CarCheckTypeEnum;
import com.molichuxing.services.property.CarInsuranceStatusEnum;
import com.molichuxing.services.property.CarInsuranceTypeEnum;
import com.molichuxing.services.property.CarYearlyInspectStatusEnum;
import com.molichuxing.services.property.HandoverTypeEnum;
import com.molichuxing.services.property.MaintenanceStatusEnum;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 车辆检验列表服务实现类
 * </p>
 * 
 * @author xuelin yi
 */
@Service("carBizService")
public class CarBizServiceImpl implements CarBizService {

	private static final Logger logger = LoggerFactory.getLogger(CarBizServiceImpl.class);

	@Resource
	private CarService carService;

	@Resource
	private CarDetailService carDetailService;

	@Resource
	private CarCheckBizService carCheckBizService;

	@Resource
	private HandoverService handoverService;

	@Resource
	private LicencePlateService licencePlateService;

	@Resource
	private CheckService checkService;

	@Resource
	private CarViolationService carViolationService;

	@Resource
	private AccidentService accidentService;

	@Resource
	private MaintenanceService maintenanceService;

	@Resource
	private InsuranceService insuranceService;

	@Resource
	private YearlyInspectService yearlyInspectService;

	@Override
	public CarDetailBizDto getCarDetail(Integer carId) {
		CarDto carDto = carService.getCarById(carId);
		if (null == carDto) {
			return null;
		}
		CarDetailDto carDetailDto = carDetailService.getCarDetailById(carId);
		LicencePlateDto licencePlateDto = licencePlateService.getLicensePlateByCarId(carId);
		return Convert.toCarDetailDto(carDto, carDetailDto, licencePlateDto);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public Integer createBizCar(VehicleCreateBizDto createBizDto) throws Exception {
		CarDto carDto = carService.getCarByVin(createBizDto.getVin());
		if (null != carDto) {
			return -1;
		}
		int resultId = carService.createCar(createBizDto);
		if (resultId > 0) {
			createBizDto.setCarId(resultId);
			int resultDetail = carDetailService.createCarDetail(createBizDto);
			if (resultDetail > 0) {
				return resultId;
			}
		}
		return -1;
	}

	/**
	 * 提车修改车辆状态、保存车辆交接单信息
	 * 
	 * @param modifyDto
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public Boolean modifyDeliveryCar(DeliveryModifyBizDto modifyDto) throws BizException {
		Boolean result = false;
		// 修改车辆状态
		if (carService.modifyDeliveryCar(modifyDto.getCarId())) {
			// 查询交接单信息
			HandoverDto handoverDto = handoverService.getHandover(modifyDto.getHandover().getOrderCode(),
					HandoverTypeEnum.DELIVERY);
			if (handoverDto == null) {
				// 不存在，新增
				HandoverCreateDto createDto = Convert.toHandoverCreateDto(modifyDto.getHandover());
				createDto.setType(HandoverTypeEnum.DELIVERY);
				handoverService.create(createDto);
			} else {
				// 存在，修改
				if (!handoverService.modify(Convert.totoHandoverModifyDto(modifyDto.getHandover(), handoverDto))) {
					logger.error("[modifyDeliveryCar]修改交接单信息失败");
					throw new BizException("修改交接单信息失败");
				}
			}
			result = true;
		}
		return result;
	}

	/**
	 * 车辆待处理统计
	 * 
	 * @return
	 */
	@Override
	public CarPendStatisticsDto getCarPendStatisticsDto() {

		CarPendStatisticsDto carPendStatisticsDto = new CarPendStatisticsDto();

		// 新车检验待处理
		carPendStatisticsDto.setNewCarInspectionPend(checkService.getPendCount(CarCheckTypeEnum.NEW_CHECK.getValue()));

		// PDI检验待处理
		carPendStatisticsDto.setPdiInspectionPend(checkService.getPendCount(CarCheckTypeEnum.PDI.getValue()));

		// 违章待处理
		carPendStatisticsDto.setViolationInspectionPend(carViolationService.getViolationCount());

		// 事故待确认
		carPendStatisticsDto.setAccidentConfirmed(
				accidentService.getAccidentCount(CarAccidentStatusEnum.ACCIDENT_NOT_CONFIRMED.getValue()));

		// 结案待确认
		carPendStatisticsDto.setClosingConfirmed(
				accidentService.getAccidentCount(CarAccidentStatusEnum.CASE_NOT_CONFIRMED.getValue()));

		// 保养将到期待保养
		carPendStatisticsDto.setMaintenanceWillExpected(
				maintenanceService.getMaintenancePendCount(MaintenanceStatusEnum.WAITING_MAINTENANCE.getValue()));

		// 保养待审核
		carPendStatisticsDto.setMaintenanceReviewed(
				maintenanceService.getMaintenancePendCount(MaintenanceStatusEnum.AUDITED.getValue()));

		// 交强险将到期待处理
		carPendStatisticsDto.setCompulsoryInspectionPend(
				insuranceService.getInsuranceTabCount(CarInsuranceTypeEnum.COMPULSORY_INSURANCE.getValue(),
						CarInsuranceStatusEnum.UNDER_WARRANTY.getValue()));

		// 商业险将到期待处理
		carPendStatisticsDto.setCommercialInspectionPend(
				insuranceService.getInsuranceTabCount(CarInsuranceTypeEnum.COMMERCIAL_INSURANCE.getValue(),
						CarInsuranceStatusEnum.UNDER_WARRANTY.getValue()));

		// 年检将到期待处理
		carPendStatisticsDto
				.setAnnualInspectionPend(yearlyInspectService.getYearlyInspectCount(CarYearlyInspectStatusEnum.NORMAL));

		return carPendStatisticsDto;
	}

	/**
	 * 还车修改车辆状态、保存车辆交接单信息、新增检验信息
	 * 
	 * @param modifyBizDto
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public Boolean modifyReturnCar(ReturnCarModifyBizDto modifyBizDto) {
		// 修改车辆状态
		if (!carService.modifyReturnCar(modifyBizDto.getCarId())) {
			logger.error("[modifyReturnCar]还车修改车辆状态失败");
			return false;
		}
		// 查询交接单信息
		HandoverDto handoverDto = handoverService.getHandover(modifyBizDto.getHandover().getOrderCode(),
				HandoverTypeEnum.RETURN);
		if (handoverDto == null) {
			// 不存在，新增
			HandoverCreateDto createDto = Convert.toHandoverCreateDto(modifyBizDto.getHandover());
			createDto.setType(HandoverTypeEnum.RETURN);
			handoverService.create(createDto);
		} else {
			// 存在，修改
			if (!handoverService.modify(Convert.totoHandoverModifyDto(modifyBizDto.getHandover(), handoverDto))) {
				logger.error("[modifyDeliveryCar]修改交接单信息失败");
				throw new BizException("修改交接单信息失败");
			}
		}
		// 新增检验数据
		checkService.create(Convert.toCheckCreateDto(modifyBizDto));

		return true;
	}

	/**
	 * 车辆列表导出
	 *
	 * @param selectParams
	 * @return
	 */
	@Override
	public List<CarBizDto> getCarListDownload(Map<String, Object> selectParams) {
		List<CarDto> carList= carService.getCarListDownload(selectParams);
		if(null == carList || carList.size() < 1){
			return null;
		}

		Map<Integer, CarDetailDto> carDetailMap=null;
		if(carList.size() > 20000){
			carDetailMap = carDetailService.getCarDetailMap();
		}else{
			List<Integer> catIdList = carList.stream().map(CarDto::getId).collect(Collectors.toList());
			carDetailMap = carDetailService.getCarDetailMapByIds(catIdList);
		}
		return Convert.toCarBizDto(carList,carDetailMap);
	}

	@Override
	public long getCarListDownloadCount(Map<String, Object> selectParams) {
		return carService.getCarListDownloadCount(selectParams);
	}

}
